<script lang="ts" setup>
import { getConsultOrderDetailAPI, sendChatMsgAPI, uploadImage } from '@/apis/quickEntry'
import { userStore } from '@/stores'
import useConsultStore from '@/stores/consult'
import { baseURL } from '@/utils/request'
import { onLoad } from '@dcloudio/uni-app'
import { io } from '@hyoga/uni-socket.io'
import type { Socket } from 'socket.io-client'
import { nextTick, ref } from 'vue'
import RoomStatus from './components/room-status.vue'
import { Status, type ConsultOrderDetailRes } from '@/types/consult'
import type { ChatMsgListData, MsgItem } from '@/types/room'
import PatientInfo from './components/patient-info.vue'
import NotifyInfo from './components/notify-info.vue'
import MessageInfo from './components/message-info.vue'
import PrescriptionInfo from './components/prescription-info.vue'
import RateInfo from './components/rate-info.vue'

const token = userStore().token
const store = useConsultStore()
const socket: Socket = io(baseURL, {
  auth: { token: `Bearer ${token}` },
  query: { orderId: store.orderId },
  transports: ['websocket', 'polling'],
  timeout: 5000,
})
const orderDetail = ref<ConsultOrderDetailRes>()
const getConsultOrderDetail = async () => {
  const res = await getConsultOrderDetailAPI({ orderId: store.orderId })
  // console.log(res)
  orderDetail.value = res.data
}
onLoad(() => {
  getConsultOrderDetail()
})
// 监听订单状态变化
socket.on('statusChange', () => {
  getConsultOrderDetail()
})
const msgList = ref<MsgItem[]>([])
const scrollIntoViewId = ref('')
// 监听 WebSocket 事件
socket.on('chatMsgList', (res: ChatMsgListData) => {
  if (res.code !== 10000) return
  res.data?.forEach((item) => {
    if (item.items) {
      msgList.value.push(
        {
          msgType: 31,
          createTime: item.createTime as string,
          msg: {
            content: item.createTime,
          },
        },
        ...item.items
      )
    }
  })
})
// 监听 receiveChatMsg 事件
socket.on('receiveChatMsg', async (message: MsgItem) => {
  // 追加到消息列表中
  msgList.value.push(message)
  // 更新消息状态，已读
  socket.emit('updateMsgStatus', message.id)
  // 通过 nextTick 等待消息列表更新
  await nextTick()
  // 滚动到最新消息
  scrollIntoViewId.value = `id-${message.id}`
})
// 发送消息
const txtMsg = ref('')
const sendMsg = async () => {
  socket.emit('sendChatMsg', {
    from: userStore().userInfo?.id,
    msg: {
      content: txtMsg.value,
    },
    msgType: 1,
    to: orderDetail.value?.docInfo?.id,
  })
  txtMsg.value = ''
}
// 选择图片
const ChooseImage = async (image: string) => {
  // 7.1 是否在问诊状态中...
  if (orderDetail.value?.status !== 3) {
    return uni.showToast({ title: '医生当前不在线!' })
  }
  // 7.2 选择图片
  const res = await uni.chooseImage({
    count: 1,
    sizeType: ['original', 'compressed'],
    sourceType: ['album', 'camera'],
  })
  const fp = res.tempFilePaths[0]
  // 7.3 上传图片
  const picture = await uploadImage(fp)
  socket.emit('sendChatMsg', {
    from: userStore().userInfo?.id,
    msg: {
      picture: picture.data,
    },
    msgType: 4,
    to: orderDetail.value?.docInfo?.id,
  })
}
</script>

<template>
  <view class="room-page">
    <!-- 此处将来填充更多代码... -->
    <RoomStatus
      v-if="orderDetail?.id"
      :status-value="orderDetail.statusValue"
      :countdown="orderDetail.countdown as number"
      :status="orderDetail.status"
    />
    <scroll-view
      refresher-enabled
      refresher-background="#f2f2f2"
      scroll-y
      style="flex: 1; overflow: hidden"
      :scroll-into-view="scrollIntoViewId"
    >
      <view class="message-container">
        <view class="message-item" v-for="item in msgList" :key="item.id" :id="`id-${item.id}`">
          <PatientInfo v-if="item.msgType === 21" :info="item.msg?.consultRecord" />
          <NotifyInfo v-else-if="item.msgType && item.msgType >= 31" :type="item.msgType">
            {{ item.msg?.content }}
          </NotifyInfo>
          <MessageInfo v-else-if="item.msgType === 1 || item.msgType === 4" :item="item" />
          <PrescriptionInfo v-else-if="item.msgType === 22" :item="item" />
          <RateInfo
            v-else-if="item.msgType === 23 || item.msgType === 24"
            :itemType="item.msgType"
          />
        </view>
      </view>
    </scroll-view>
    <!-- 发送消息 -->
    <view class="message-bar">
      <template v-if="true">
        <uni-easyinput
          :disabled="orderDetail?.status !== Status.ZiXunZhong"
          v-model="txtMsg"
          @confirm="sendMsg"
          :clearable="false"
          :input-border="false"
          placeholder-style="font-size: 32rpx; color: #c3c3c5;"
          placeholder="问医生"
        />
        <view class="image-button" @click="ChooseImage">
          <uni-icons size="40" color="#979797" type="image"></uni-icons>
        </view>
      </template>
      <button v-else class="uni-button">咨询其它医生</button>
    </view>
  </view>
</template>

<style lang="scss">
@import './index.scss';
</style>
